package kr.co.hk.fac;

import java.util.ArrayList;
import java.util.List;

import kr.co.hk.R;
import kr.co.hk.util.MapUtil;
import kr.co.hk.util.MyLocationListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class FacMain extends Activity implements OnClickListener {
	private String bestProvider; // 현재 위치값을 가져오기위한 프로바이더. (network, gps)
	private LocationManager locM; // 위치 매니저
	private LocationListener locL; // 위치 리스너
	private Location currentLocation; // 현재 위치
	private String latlng = "";
	private String addrSplit = "";
	/** Called when the activity is first created. */
	private EditText etSearch;
	private int localNum;
	private ArrayList<String> matches;
	private static final int REQUEST_CODE = 1234;
	private boolean pageEx = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fac_main);
		etSearch = (EditText) findViewById(R.id.etSearch);
		Button btnSearch = (Button) findViewById(R.id.btnSearch);
		Button btnVoiceSearch = (Button) findViewById(R.id.facVoiceSearch);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setSpeedRequired(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		// 위치 매니저를 시스템으로부터 받아온다.
		locM = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// 사용가능한 적절한 프로바이더를 받아온다.
		// network (보통 3G망,Wifi AP 위치정보)또는 gps 둘중 하나로 설정된다.
		bestProvider = locM.getBestProvider(new Criteria(), true);

		// 기기에 가지고 있는 마지막 위치정보로 현재위치를 초기 설정한다.
		currentLocation = locM.getLastKnownLocation(bestProvider);

		// 위치 리스너 초기화
		locL = new MyLocationListener();
		// 위치 매니저에 위치 리스너를 셋팅한다.
		// 위치 리스너에서 10000ms (10초) 마다 100미터 이상 이동이 발견되면 업데이트를 하려한다.
		locM.requestLocationUpdates(bestProvider, 10000, 100, locL);

		latlng = currentLocation.getLatitude() + ","
				+ currentLocation.getLongitude();

		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
			btnVoiceSearch.setOnClickListener(this);
		} else {
			btnVoiceSearch.setEnabled(false);
			btnVoiceSearch.setText("Not Rec");
		}

		Resources r = getResources();
		String[] searchFacCl = r.getStringArray(R.array.searchFacCl);
		String[] spinnerArr = new String[searchFacCl.length + 1];
		for (int i = 0; i < spinnerArr.length; i++) {
			if (i == 0) {
				spinnerArr[i] = "시설분류를 선택하세요!!";
			} else {
				spinnerArr[i] = searchFacCl[i - 1];
			}
		}

		String[] localArr = r.getStringArray(R.array.searchLocal);

		GridView gv = (GridView) findViewById(R.id.gridview);
		Spinner spinner = (Spinner) findViewById(R.id.locationSpinner);

		ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
				R.layout.fac_grid_view, localArr);
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerArr);

		spinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerAdapter);
		gv.setAdapter(aa);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				if (position != 0) {
					boolean isStatus = getAddrSplit(latlng);
					if (pageEx) {
						excePro();

					} else {
						if (isStatus) {
							Intent intent = new Intent(FacMain.this,
									FacList.class);
							intent.putExtra("groupNum", position - 1);
							intent.putExtra("localNum", localNum);
							startActivity(intent);
						} else {
							toast("죄송합니다. \n 현재 지역을 찾을수 없습니다.");
						}
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent intent = new Intent(FacMain.this, FacGroupList.class);
				intent.putExtra("localNum", position);
				startActivity(intent);
			}

		});

		btnSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String searchKeyword = etSearch.getText().toString();
				if (searchKeyword.equals("")) {
					toast("시설명을 입력하세요");
				} else {
					Intent intent = new Intent(FacMain.this, FacList.class);
					intent.putExtra("searchKeyword", searchKeyword);
					startActivity(intent);
				}

			}
		});

	}

	public void onClick(View v) {
		if (v.getId() == R.id.facVoiceSearch) {
			startVoiceRecognitionActivity();
		}
	}

	private void startVoiceRecognitionActivity() {
		try {
			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
					RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "검색어를 말하세요!");
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException ex) {
			Toast.makeText(FacMain.this, "Activity Not Found",
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
			matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			Intent intent = new Intent(FacMain.this, FacList.class);
			intent.putExtra("searchKeyword", matches.get(0));
			startActivity(intent);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean getAddrSplit(String latlng) {

		boolean isStatus = false;
		String url = "http://maps.google.co.kr/maps/api/geocode/json?latlng="
				+ latlng + "&sensor=false";
		MapUtil mapUtil = new MapUtil();
		String jString = mapUtil.getResultConn(url);
		try {
			localNum = 0;
			JSONObject jObject = new JSONObject(jString);
			if (!jObject.equals(null)) {
				String status = jObject.getString("status");
				if (status.equals("OK")) {
					JSONArray resultArr = new JSONArray(jObject
							.getString("results"));
					String formatted_address = resultArr.getJSONObject(0)
							.getString("formatted_address");
					String[] addresArr = formatted_address.split(" ");
					addrSplit = addresArr[1];
					localNum = chageAddr(addrSplit);
					isStatus = true;
				} else {
					isStatus = false;
				}

			} else {
				isStatus = false;
			}

		} catch (JSONException e) {
			pageEx = true;
			e.printStackTrace();
		}
		return isStatus;

	}

	private int chageAddr(String addr) {
		int num = 0;
		if (addr.contains("서울")) {
			num = 0;
		} else if (addr.contains("경기")) {
			num = 1;
		} else if (addr.contains("인천")) {
			num = 2;
		} else if (addr.contains("강원")) {
			num = 3;
		} else if (addr.contains("충청북")) {
			num = 4;
		} else if (addr.contains("대전")) {
			num = 5;
		} else if (addr.contains("충청남")) {
			num = 6;
		} else if (addr.contains("대구")) {
			num = 7;
		} else if (addr.contains("경상북")) {
			num = 8;
		} else if (addr.contains("부산")) {
			num = 9;
		} else if (addr.contains("울산")) {
			num = 10;
		} else if (addr.contains("경상남")) {
			num = 11;
		} else if (addr.contains("전라북")) {
			num = 12;
		} else if (addr.contains("광주")) {
			num = 13;
		} else if (addr.contains("전라남")) {
			num = 14;
		} else if (addr.contains("제주")) {
			num = 15;

		} else {
			num = 0;
		}
		return num;
	}

	private void excePro() {
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

}
